package com.example.oa;


import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter("/*")
public class PseudoSignInFilter implements Filter{
    @Override
    public void destroy() {
        System.out.println("销毁时调用");

    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        //1.获取资源请求的路径,强制转换

        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();

//        System.out.println("判断是否需要放行的URI：" + uri);

        //放行需要的页面
        if (uri.contains("/test")) {
            chain.doFilter(req, response);
        } else { //  访问其他资源，就判断是否登录

            Object obj = req.getSession().getAttribute("role"); // 判断是否有角色存在
            if (obj != null) {
                chain.doFilter(request, response);
            } else {  //如果没有，则跳转到登录界面
                req.setAttribute("error", "登录错误！");
                req.getRequestDispatcher("test/index.jsp").forward(req, response);
            }
        }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }
}